package com.xinjian.jianba.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.xinjian.jianba.dao.dwmid.UserInfoDao;
import com.xinjian.jianba.dao.dwmid.UserPayConfigDao;
import com.xinjian.jianba.dto.CheckCodeDto;
import com.xinjian.jianba.enity.UserInfoEnity;
import com.xinjian.jianba.enity.UserPayConfigEnity;
import com.xinjian.jianba.exception.BusinessException;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.service.RedisService;
import com.xinjian.jianba.service.SmsService;
import com.xinjian.jianba.utils.Constants;
import com.xinjian.jianba.utils.JianBaEnum;
import com.xinjian.jianba.utils.JsonUtil;
import com.xinjian.jianba.utils.SMSUtils;

@Service
public class SmsServiceImpl implements SmsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserInfoDao uerInfoDao;

    @Autowired
    private UserPayConfigDao userPayConfigDao;

    @Override
    public void sendSms(String mobile, int type, Long userId) throws Exception {
        String key = null;

        UserInfoEnity userInfo = new UserInfoEnity();
        userInfo.setMobile(mobile);
        userInfo.setIs_register(1);// 当is_register值为1是表示注册成功
        List<UserInfoEnity> userInfoList = uerInfoDao.select(userInfo);
        // 注册时
        if (type == 0) {
            // 用户已经注册
            if (!CollectionUtils.isEmpty(userInfoList)) {
                throw new BusinessException(ResponseCode.ERROR, "手机号已经注册!");
            }
            // 找回密码时
        } else if (type == 1) {
            // 用户未注册
            if (CollectionUtils.isEmpty(userInfoList)) {
                throw new BusinessException(ResponseCode.ERROR, "手机号未注册!");
            }
        } else if (type == 2) {
            if (userId == null) {
                throw new BusinessException(ResponseCode.ERROR, "用户id不能为空!");
            }
            UserPayConfigEnity userPayConfig = userPayConfigDao.selectByUserIdOrMobile(userId, mobile);
            if (userPayConfig == null) {
                throw new BusinessException(ResponseCode.ERROR, "用户id与手机号不匹配!");
            }
        }

        if (type == 0) {
            key = Constants.REGISTER__SMS_CODE_PRE.concat(mobile);
        } else if (type == 1) {
            key = Constants.FORGET_PASSWORDSMS_SMS_CODE_PRE.concat(mobile);
        } else if (type == 2) {
            key = Constants.PAY_SMS_CODE_PRE.concat(mobile);
        }

        String isExitCode = redisService.get(key);
        if (StringUtils.isNotBlank(isExitCode)) {
            // 失败：状态为0
            throw new BusinessException(ResponseCode.ERROR, ResponseCode.SMS_EXIT_MSG);
        }
        // 发送手机短信
        String phoneCode = RandomStringUtils.random(Constants.CAPTCHA_LENGTH, Constants.STR_NUM);

        JSONObject smsContent = new JSONObject();
        smsContent.put("code", phoneCode);

        // 发短信
        SendSmsResponse response = SMSUtils.sendSms(mobile, smsContent.toJSONString());
        LOGGER.info("----response---" + JsonUtil.getJsonString(response));

        if (!"OK".equals(response.getCode())) {
            // 失败：状态为0
            throw new BusinessException(ResponseCode.ERROR, ResponseCode.SMS_ERROR_MSG);
        } else {
            // // 成功：状态为1
            redisService.set(key, phoneCode);
            redisService.expire(key, Constants.ACTIVITY_TIME_1_MINIC);
        }

    }

    /**
     * 验证码校验
     *
     */
    @Override
    public Map<String, Object> checkCode(CheckCodeDto checkCodeDto) throws Exception {
        String redisCode = null;
        if (checkCodeDto.getType().intValue() == 0) {
            redisCode = redisService.get(Constants.REGISTER__SMS_CODE_PRE.concat(checkCodeDto.getMobile()));
        } else if (checkCodeDto.getType().intValue() == 1) {
            redisCode = redisService.get(Constants.FORGET_PASSWORDSMS_SMS_CODE_PRE.concat(checkCodeDto.getMobile()));
        } else if (checkCodeDto.getType().intValue() == 2) {
            redisCode = redisService.get(Constants.PAY_SMS_CODE_PRE.concat(checkCodeDto.getMobile()));
        }

        LOGGER.info(redisCode + "----checkCode---" + checkCodeDto.getCode());

        if (StringUtils.isBlank(redisCode)) {
            throw new BusinessException(ResponseCode.ERROR, Constants.CODE_OUT_OF_DATE);
        }
        if (!redisCode.equals(checkCodeDto.getCode())) {
            throw new BusinessException(ResponseCode.ERROR, Constants.CODE_ERROR);
        }

        Long userId = null;
        if (checkCodeDto.getType().intValue() == 1) {
            UserInfoEnity userInfo = new UserInfoEnity();
            userInfo.setMobile(checkCodeDto.getMobile());
            userInfo.setUsrStatus(JianBaEnum.UserStatusEnum.NORMAL.getValue());
            List<UserInfoEnity> userInfoList = uerInfoDao.select(userInfo);
            if (!CollectionUtils.isEmpty(userInfoList)) {
                userId = userInfoList.get(0).getId();
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", userId);
        return map;
    }
}
